import type {
    BaseFormComponentType,
    ExtendedFormApi,
    JcxFormProps,
} from './types';

import {defineComponent, h, isReactive, onBeforeUnmount, watch} from 'vue';

import {useStore} from '@/utils/shared/store';

import {FormApi} from './form-api';
import JcxUseForm from './jcx-use-form.vue';

export function useJcxForm<
    T extends BaseFormComponentType = BaseFormComponentType,
>(options: JcxFormProps<T>) {
    const IS_REACTIVE = isReactive(options);
    const api = new FormApi(options);
    const extendedApi: ExtendedFormApi = api as never;
    extendedApi.useStore = (selector) => {
        return useStore(api.store, selector);
    };

    const Form = defineComponent(
        (props: JcxFormProps, {attrs, slots}) => {
            onBeforeUnmount(() => {
                api.unmount();
            });
            api.setState({...props, ...attrs});
            return () =>
                h(JcxUseForm, {...props, ...attrs, formApi: extendedApi}, slots);
        },
        {
            inheritAttrs: false,
            name: 'JcxUseForm',
        },
    );
    // Add reactivity support
    if (IS_REACTIVE) {
        watch(
            () => options.schema,
            () => {
                api.setState({schema: options.schema});
            },
            {immediate: true},
        );
    }

    return [Form, extendedApi] as const;
}
